import axios from 'axios'
import type { AxiosRequestConfig, AxiosResponse }  from 'axios'

// 请求基础路径
const baseURL: string = process.env.VUE_APP_BASE_DEV || ''

// 创建axios实例
const service = axios.create({
  baseURL,
  timeout: 10000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

// request拦截器
service.interceptors.request.use(
  config=> {
    config.headers.Accept = 'application/json'
    config.url = baseURL + config.url
    config.headers.Authorization = ''
    return config
  },
  (error: any) => {
    console.error(error) // for debug
    Promise.reject(error)
  }
)

// response拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.status === 200) {
      return response.data
    } else {
      return Promise.reject(response)
    }
  },
  (error: any) => {
    console.error(error) // for debug
    return Promise.reject(error)
  }
)

/**
 * 封装请求方法
 * @param {AxiosRequestConfig} config
 * @returns {Promise<any>}
 */
const request = (config: AxiosRequestConfig): Promise<any> => {
  return service(config)
}

export default request